package com.huluobo.a2211mdmdemo.views

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.lib_base.BaseTitle
import com.hyphenate.EMCallBack
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMMessage.ChatType
import com.hyphenate.chat.EMTextMessageBody
import kotlinx.coroutines.launch
import org.w3c.dom.Text
import java.text.SimpleDateFormat
import kotlin.coroutines.coroutineContext

/**
 *  Created by LC on 2025/5/9.
 */

data class ChatBean(val contact: String, val chatType: ChatType)

@Composable
fun ChatPage(navHostController: NavHostController, json: String) {
    val chatBean = Gson().fromJson(json, ChatBean::class.java)

    //聊天数据源
    val messageList = remember {
        SnapshotStateList<EMMessage>()
    }

    //发送的一条消息内容
    var message by remember {
        mutableStateOf("")
    }

    //当前列表的状态
    val listState = rememberLazyListState()

    //控制列表滚动到最下方
    val coroutineScope = rememberCoroutineScope()

    //消息监听器
    val messageListener = EMMessageListener {
        messageList.addAll(it)
        coroutineScope.launch {
            listState.scrollToItem(messageList.size - 1)
        }
    }

    DisposableEffect(Unit) {
        //带生命周期的协程作用域
        //初始化时添加消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        //当page销毁时移除监听器
        onDispose {
            EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        }
    }

    Scaffold(
        bottomBar = {
            OutlinedTextField(
                value = message,
                onValueChange = { message = it },
                Modifier.fillMaxWidth(),
                trailingIcon = {
                    Icon(imageVector = Icons.Default.Send, contentDescription = "", Modifier.clickable {
                        //构建一条消息实体
                        val emMessage = EMMessage.createTextSendMessage(message, chatBean.contact)
                        //设置消息的类型
                        emMessage.chatType = chatBean.chatType
                        //设置消息回调,发送成功后需要添加数据源
                        emMessage.setMessageStatusCallback(object : EMCallBack {
                            override fun onSuccess() {
                                messageList.add(emMessage)
                                message = ""
                                coroutineScope.launch {
                                    listState.scrollToItem(messageList.size - 1)
                                }
                            }

                            override fun onError(code: Int, error: String?) {
                                ToastUtils.showLong("发送消息失败:$code,error:$error")
                            }
                        })
                        //发送消息
                        EMClient.getInstance().chatManager().sendMessage(emMessage)
                    })
                })
        }
    ) {
        Column(
            Modifier
                .padding(it)
                .padding(20.dp)
                .fillMaxWidth()
        ) {
            BaseTitle(title = "与${chatBean.contact}聊天", navHostController = navHostController)
            Spacer(modifier = Modifier.height(10.dp))
            Divider(thickness = 0.5.dp)
            Spacer(modifier = Modifier.height(10.dp))
            LazyColumn(verticalArrangement = Arrangement.spacedBy(10.dp), state = listState, content = {
                items(messageList) {
                    ChatItem(message = it)
                }
            })
        }
    }
}

@Composable
fun ChatItem(message: EMMessage) {
    when (message.direct()) {
        EMMessage.Direct.SEND -> {
            Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = "$time", color = Color.LightGray)
                Row(
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .padding(10.dp)
                        .fillMaxWidth()
                ) {
                    Text(text = (message.body as EMTextMessageBody).message)
                    Spacer(modifier = Modifier.width(10.dp))
                    AsyncImage(
                        model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                        contentDescription = "",
                        Modifier
                            .size(40.dp)
                            .clip(RoundedCornerShape(5.dp)),
                        contentScale = ContentScale.Crop
                    )
                }
            }
        }

        EMMessage.Direct.RECEIVE -> {
            Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = "$time", color = Color.LightGray)
                Row(
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .padding(10.dp)
                        .fillMaxWidth()
                ) {
                    AsyncImage(
                        model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                        contentDescription = "",
                        Modifier
                            .size(40.dp)
                            .clip(RoundedCornerShape(5.dp)),
                        contentScale = ContentScale.Crop
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    Text(text = (message.body as EMTextMessageBody).message)
                }
            }
        }
    }
}